package com.ruoyi.grpc;


import com.google.common.annotations.VisibleForTesting;
import com.ruoyi.common.utils.Base64;
import com.ruoyi.grpc.generate.AudioStreaming;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HeaderClientInterceptor implements ClientInterceptor {

    private static final Logger log = LoggerFactory.getLogger(HeaderClientInterceptor.class);

    @VisibleForTesting
    static final Metadata.Key<String> CUSTOM_HEADER_KEY =
            Metadata.Key.of("custom_client_header_key", Metadata.ASCII_STRING_MARSHALLER);

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
                                                               CallOptions callOptions, Channel next) {
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                // @1 在Header中设置需要透传的值
                headers.put(CUSTOM_HEADER_KEY, "customRequestValue");
                AudioStreaming.InitRequest initRequest = AudioStreaming.InitRequest.newBuilder()
                        .setEnableLongSpeech(true)
                        .setEnableChunk(true)
                        .setEnableFlushData(true)
                        .setProductId("123")
                        .setSamplePointBytes(2)
                        .setSendPerSeconds(1.0)
                        .setSleepRatio(1.0)
                        .setAppName("asr")
                        .setLogLevel(1)
                        .setUserName("zhoujun")
                        .setExpireTime("1")
                        .setToken("1234")
                        .setVersion(AudioStreaming.ProtoVersion.VERSION_1)
                        .setExtraInfo("1")
                        .build();
                String metaString = Base64.encode(initRequest.toByteArray());
                headers.put(Metadata.Key.of("audio_meta", Metadata.ASCII_STRING_MARSHALLER), metaString);
                log.info("init request: \n{}meta_string: {}", initRequest.toString(), metaString);
                super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(
                        responseListener) {
                    @Override
                    public void onHeaders(Metadata headers) {
                        // @2 获取从服务端返回的Header信息
                        log.info("header received from server:" + headers);
                        super.onHeaders(headers);
                    }
                }, headers);
            }
        };
    }

}
